﻿using SwParaPlatform2.logger;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace SwParaPlatform2.dlgUIConfig
{
    public partial class dlgUIConfigView : PageBase, IView
    {
        public event System.EventHandler LoadDataBtnClicked;
        public event System.EventHandler SaveBtnClicked;
        public event System.EventHandler UpBtnClicked;
        public event System.EventHandler DownBtnClicked;

        public event EventHandler<int> DelEditRow;
        public event EventHandler<string> SelectRow;
        public event EventHandler<string> OnCheckedChanged;
        public event EventHandler<GenericEventArgs<Dictionary<string, object>>> AddEditRow;
        public event EventHandler<GenericEventArgs<(int, Dictionary<string, object>)>> ChangeEditRow;
        public event EventHandler<GenericEventArgs<List<string>>> SaveOrder;

        public event Action<string> InputTypeChanged;

        public UIConfigDelegate mainDelegate;
        private readonly ISwParaInterface _commonInterface;
        private string lastValidText = string.Empty;  // 保存上一次合法的输入内容
        public IModel model;

        event System.EventHandler IView.NextClicked
        {
            add { base.NextClicked += value; }
            remove { base.NextClicked -= value; }
        }

        public dlgUIConfigView():base()
        {
            InitializeComponent();
            Init();
            _commonInterface = new SwParaInterface();
            model = UIConfigModel.Instance;
            model.ClearData(true);
            mainDelegate = new UIConfigDelegate(this, model);
        
        }

        public override void Cleanup()
        {
            UpBtnClicked = null;
            DownBtnClicked = null;
            SaveBtnClicked = null;
            LoadDataBtnClicked = null;
            OnCheckedChanged = null;
            DelEditRow = null;
            SelectRow = null;
            AddEditRow = null;
            ChangeEditRow = null;
            InputTypeChanged = null;

            mainDelegate.DisConnect();
            mainDelegate = null;

            model.ClearData(false);
        }

        public void Init()
        {
            BindButton(NextPageBtn, PrevPageBtn);
            OnSelectEditType("");
            UIConfigGrid.SelectionChanged += DataGridView_SelectionChanged;

            DefaultInput.Validating += InputTextBox_Validating;
            
            UIConfigGrid.Columns["OrderCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIConfigGrid.Columns["ArgCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIConfigGrid.Columns["MaxCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIConfigGrid.Columns["MinCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIConfigGrid.Columns["DefaultCol"].AutoSizeMode = DataGridViewAutoSizeColumnMode.None;
            UIConfigGrid.Columns["OrderCol"].Width = 60; // 设置固定宽度
            UIConfigGrid.Columns["ArgCol"].Width = 100; // 设置固定宽度
            UIConfigGrid.Columns["MaxCol"].Width = 60; // 设置固定宽度
            UIConfigGrid.Columns["MinCol"].Width = 60; // 设置固定宽度
            UIConfigGrid.Columns["DefaultCol"].Width = 60; // 设置固定宽度
        }

        public void ShowError(string message)
        {
            // 显示错误信息
            MessageBox.Show(message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        #region UI事件
        protected virtual void OnAddDataClick(GenericEventArgs<Dictionary<string, object>> e)
        {
            AddEditRow?.Invoke(this, e);
        }

        protected virtual void OnSaveOrder(GenericEventArgs<List<string>> e)
        {
            SaveOrder?.Invoke(this, e);
        }

        public void ClearEditData()
        {
            EditListBtn.Tag = null;

            ArgInput.Text = "";
            ShowRuleInput.Text = "";
            EqualTextBox.Text = "";
            MaxInput.Text = "";
            MinInput.Text = "";
            DefaultInput.Text = "";

            SetComboBoxValue("");
        }

        public void DoAddData()
        {
            string iRowCount = UIConfigGrid.Rows.Count.ToString();
            string sArg = ArgInput.Text;
            string sInputType = InputTypeList.Text;
            string sShowRule = ShowRuleInput.Text;
            string sEqual = EqualTextBox.Text;
            string sMax = MaxInput.Text;
            string sMin = MinInput.Text;
            string sDefault = DefaultInput.Text;
            string sRowPicPath = pictureBox1.ImageLocation;
            string sUnit = UnitSelect.Text;

            var result = XmlHandler.ValidateElementName(sArg, "备注");
            if (!result.IsValid)
            {
                ShowToolTip(ArgInput, $"设置备注名失败。{result.ViolationReason}");
                return;
            }

            List<string> InputList;

            if (EditListBtn.Visible)
            {
                if (EditListBtn.Tag is List<string> TagInputList)
                {
                    // 读取并显示列表内容
                    InputList = TagInputList;
                }
                else
                {
                    MessageBox.Show("No list found in the Tag.");
                    InputList = null;
                }
            }
            else
            {
                if (EqualTextBox.Visible)
                {
                    bool isValid = AreTextBoxesValid(EqualTextBox.Text, MaxInput.Text, MinInput.Text);

                    if (!isValid)
                    {
                        MessageBox.Show("最大值、最小值、等差必须为数字或留空!");
                        return;
                    }

                    int iEqual;
                    int iMax;
                    int iMin;

                    int.TryParse(sEqual, out iEqual);
                    int.TryParse(sMax, out iMax);
                    int.TryParse(sMin, out iMin);
                    InputList = GenerateList(iMin, iMax, iEqual);

                    if (InputList == null)
                    {
                        return;
                    }
                }
                else
                {
                    InputList = null;
                }


            }

            var dSubLineData = new Dictionary<string, object>
        {
            { "序号", UIConfigGrid.Rows.Count },
            { "参数", sArg },
            { "单位", sUnit },
            { "输入类型", sInputType },
            { "显示规则", sShowRule },
            { "最大值", sMax },
            { "最小值", sMin },
            { "默认值", sDefault },
            { "等差", sEqual },
            { "输入列表", InputList },
            { "示例图", sRowPicPath },
        };

            var dOneLineData = new Dictionary<string, object>
            {
                {sArg, dSubLineData },
            };
            OnAddDataClick(new GenericEventArgs<Dictionary<string, object>>(dOneLineData));
            ClearEditData();
        }

        private void SelectMainViewPic()
        {
            // 文件夹路径A
            string folderAPath = $@"{DataStore.Instance.sWorkingPath}";
            string picFolderPath = Path.Combine(folderAPath, "pic");
            string viewImagePath = Path.Combine(picFolderPath, $"{ArgInput.Text}");

            // 打开文件选择对话框
            using (OpenFileDialog openFileDialog = new OpenFileDialog())
            {
                openFileDialog.Filter = "Image Files|*.jpg;*.jpeg;*.png;*.bmp";  // 过滤文件类型为图片
                if (openFileDialog.ShowDialog() == DialogResult.OK)
                {
                    string selectedFilePath = openFileDialog.FileName;  // 获取选择的图片路径

                    // Step 1: 检查目标文件夹是否存在，如果不存在则创建
                    if (!Directory.Exists(picFolderPath))
                    {
                        Directory.CreateDirectory(picFolderPath);
                    }

                    // Step 2: 检查是否存在同名文件，若存在则删除
                    if (File.Exists(viewImagePath))
                    {
                        File.Delete(viewImagePath);
                    }

                    // Step 3: 复制选择的图片文件到目标文件夹并命名为 参数名
                    string viewFilePath = Path.Combine(picFolderPath, $"{ArgInput.Text}" + Path.GetExtension(selectedFilePath));  // 保留扩展名

                    if (File.Exists(viewFilePath))
                    {
                        File.Delete(viewFilePath);
                    }

                    File.Copy(selectedFilePath, viewFilePath);

                    // Step 4: 在 PictureBox 中显示复制的图片
                    // pictureBox1.ImageLocation = viewFilePath;
                    RefreshSelectPic(viewFilePath);

                    // 返回复制文件的路径
                    //OnSelectMainViewPic?.Invoke(this, viewFilePath);
                }
            }
        }

        public void OnNumLimitChecked(object sender, EventArgs e)
        {
            // 将sender转换为TextBox对象
            TextBox textBox = sender as TextBox;

            if(MaxInput.Text == "" || MinInput.Text == "")
            {
                return;
            }
            // 获取当前输入的值
            if (double.TryParse(MaxInput.Text, out double maxValue) && double.TryParse(MinInput.Text, out double minValue))
            {
                if (maxValue < minValue)
                {
                    ShowToolTip(textBox, "最大值不能小于最小值");
                    return;
                }

                if (DefaultInput.Text == "")
                {
                    return;
                }

                // 检查默认值是否在最大值和最小值之间
                if (double.TryParse(DefaultInput.Text, out double defaultValue))
                {
                    if (defaultValue < minValue || defaultValue > maxValue)
                    {
                        ShowToolTip(textBox, "输入值不在范围内");
                        return;
                    }
                }
            }
        }

        #endregion

        #region 收到数据事件
        public void OnSelectPara(Dictionary<string, object> dSelectData)
        {
            string sPara = (string)dSelectData["参数"];
            string sInputType = (string)dSelectData["输入类型"];
            string sUnit = (string)dSelectData["单位"];
            string sMax = (string)dSelectData["最大值"];
            string sMin = (string)dSelectData["最小值"];
            string sDefault = (string)dSelectData["默认值"];
            string sEqual = (string)dSelectData["等差"];
            string sShowRule = (string)dSelectData["显示规则"];
            string sRowPicPath = (string)dSelectData["示例图"];
            var InputListObj = dSelectData["输入列表"];

            ArgInput.Text = sPara;
            ShowRuleInput.Text = sShowRule;
            EqualTextBox.Text = sEqual;
            MaxInput.Text = sMax;
            MinInput.Text = sMin;
            DefaultInput.Text = sDefault;
            UnitSelect.Text = sUnit;

            SetComboBoxValue(sInputType);
            RefreshSelectPic(sRowPicPath);
            checkBox1.Checked = false;

            if (EditListBtn.Visible)
            {
                if(InputListObj is List<string> InputList)
                {
                    EditListBtn.Tag = InputList;
                }
                
            }
        }

        public void SetInputTypeList(List<string> inputTypeList)
        {
            InputTypeList.Items.Clear();
            foreach (var item in inputTypeList)
            {
                InputTypeList.Items.Add(item);
            }
        }

        public void OnSelectEditType(string sSelectType)
        {
            bool bSelectCustom = sSelectType == "下拉列表（自定义）";
            bool bSelectEqual = sSelectType == "下拉列表（等差）";
            bool bSelectFree = sSelectType == "自由填写";

            label_Equal.Visible = bSelectEqual;
            EqualTextBox.Visible = bSelectEqual;
            label_Drop.Visible = bSelectCustom;
            EditListBtn.Visible = bSelectCustom;

            MaxInput.Enabled = bSelectEqual || bSelectFree;
            MinInput.Enabled = bSelectEqual || bSelectFree;

            if(!bSelectCustom && !bSelectEqual)
            {
                EqualTextBox.Text = "";
            }
        }

        public void RefreshDataGrid(List<KeyValuePair<string, Dictionary<string, object>>> lSortDataList)
        {
            try
            {
                UIConfigGrid.Rows.Clear();
                foreach (var kv in lSortDataList)
                {
                    var rowIndex = UIConfigGrid.Rows.Add();
                    var row = UIConfigGrid.Rows[rowIndex];
                    var innerDict = kv.Value;
                    foreach (var column in kv.Value)
                    {
                        // 通过列标题判断
                        foreach (DataGridViewColumn dgvColumn in UIConfigGrid.Columns)
                        {
                            if (dgvColumn.HeaderText == column.Key)
                            {
                                if (dgvColumn.HeaderText == "输入列表")
                                {
                                    string sJoinList = "";
                                    if(column.Value == null)
                                    {

                                    }
                                    else if (column.Value is string sStringList)
                                    {
                                        sJoinList = sStringList;
                                    }
                                    else
                                    {
                                        List<string> items = (List<string>)column.Value;
                                        sJoinList = string.Join(",", items);

                                    }
                                    row.Cells[dgvColumn.Index].Value =  sJoinList;
                                }
                                else if(dgvColumn.HeaderText == "示例图")
                                {
                                    row.Cells[dgvColumn.Index].Tag = column.Value;
                                    row.Cells[dgvColumn.Index].Value = "示例图";
                                }
                                else
                                {
                                    row.Cells[dgvColumn.Index].Value = column.Value;
                                }
                                break;
                            }
                        }
                    }
                }
                UIConfigGrid.ClearSelection();
            }
            catch
            {
                Logger.Instance.Log($"加载表格失败: {this.GetHashCode()}");
            }
            
        }

        private void DoSaveOrder()
        {
            List<string> argList = new List<string>();

            // 遍历DataGridView中的每一行
            foreach (DataGridViewRow row in UIConfigGrid.Rows)
            {
                // 确保当前行不是空行（如新添加的行）
                if (!row.IsNewRow)
                {
                    // 获取"ArgCol"列对应的单元格值
                    var cellValue = row.Cells["ArgCol"].Value;

                    // 确保单元格值不为null
                    if (cellValue != null)
                    {
                        argList.Add(cellValue.ToString());
                    }
                }
            }
            OnSaveOrder(new GenericEventArgs<List<string>>(argList));
        }

        private void DelGridCol()
        {
            DelEditRow?.Invoke(this, 0);
        }

        public void OnSelectIndex(int iIndex)
        {
            UIConfigGrid.ClearSelection(); // 先清除现有选中状态
            UIConfigGrid.Rows[iIndex].Selected = true; // 选中
        }
        
        public void RefreshSelectPic(string sPath)
        {
            pictureBox1.ImageLocation = sPath;
            checkBox1.Enabled = !string.IsNullOrEmpty(pictureBox1.ImageLocation);
        }

        #endregion

        #region 内部调用

        #endregion

        #region 杂项

        public bool AreTextBoxesValid(string equalTextBoxContent, string maxInputContent, string minInputContent)
        {
            // 判断是否所有输入框均为空
            bool allEmpty = string.IsNullOrEmpty(equalTextBoxContent) && string.IsNullOrEmpty(maxInputContent) && string.IsNullOrEmpty(minInputContent);

            // 判断是否所有输入框均为数字
            bool allNumbers = int.TryParse(equalTextBoxContent, out _) && int.TryParse(maxInputContent, out _) && int.TryParse(minInputContent, out _);

            // 当所有输入框均为空，或者所有输入框均为数字时，返回 true，否则返回 false
            return allEmpty || allNumbers;
        }

        public static List<string> GenerateList(int minValue, int maxValue, int step)
        {
            List<string> result = new List<string>();

            // 检查输入值的有效性
            if (minValue > maxValue || step <= 0)
            {
                MessageBox.Show("无法生成列表：最小值必须小于或等于最大值，且等差必须为正数。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return null;
            }

            for (int i = minValue; i <= maxValue; i += step)
            {
                result.Add(i.ToString());
            }

            // 检查是否生成了有效的列表
            if (result.Count == 0)
            {
                MessageBox.Show("无法生成列表：参数不足以生成有效的列表。", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return result;
        }

        // 手动设置 ComboBox 的选定值并触发事件
        private void SetComboBoxValue(string value)
        {
            int index = InputTypeList.Items.IndexOf(value);
            if (index >= 0)
            {
                InputTypeList.SelectedIndex = index; // 设置选定值
                InputTypeList_SelectedIndexChanged(InputTypeList, EventArgs.Empty); // 手动触发事件
            }
        }

        public void ReadCustomList(string sInputList)
        {
            char[] separators = new char[] { ',', '，' };
            List<string> partsList = new List<string>(sInputList.Split(separators, StringSplitOptions.RemoveEmptyEntries));

            EditListBtn.Tag = partsList;

            List<double> numericValues = new List<double>();
            bool allNumbers = true;
            foreach (var part in partsList)
            {
                if (double.TryParse(part, out double number))
                {
                    numericValues.Add(number);
                }
                else
                {
                    allNumbers = false;
                    break;
                }
            }
            if(partsList.Count > 0)
            {
                string DefaultUnit = partsList[0];
                DefaultInput.Text = DefaultUnit;
            }

            if (allNumbers && numericValues.Any())
            {
                double max = numericValues.Max();
                double min = numericValues.Min();
                MaxInput.Text = max.ToString();
                MinInput.Text = min.ToString();
                UnitSelect.Text = "mm";
                Logger.Instance.Log($"最大值: {max}, 最小值: {min}");
            }
            else
            {
                UnitSelect.Text = " ";
                Logger.Instance.Log("列表内容为非纯数字或列表为空:");
            }
        }

        private void ShowToolTip(Control control, string message)
        {
            ToolTip toolTip = new ToolTip();
            toolTip.IsBalloon = true;
            toolTip.Show(message, control, 0, -50, 2000); // 在控件上方显示，持续3秒
        }


        #endregion

        private void InputTypeList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (InputTypeList.SelectedItem != null)
            {
                InputTypeChanged?.Invoke(InputTypeList.SelectedItem.ToString());
            }
        }

        private void DataGridView_SelectionChanged(object sender, EventArgs e)
        {
            if (UIConfigGrid.SelectedRows.Count > 0)
            {
                var selectedRow = UIConfigGrid.SelectedRows[0];
                // 确保“参数”列存在
                if (UIConfigGrid.Columns["ArgCol"] != null)
                {
                    // 获取名为“参数”的列的索引
                    int columnIndex = UIConfigGrid.Columns["ArgCol"].Index;
                    // 获取选中行中“参数”列的值
                    var cellValue = selectedRow.Cells[columnIndex].Value;
                    if (cellValue != null) // 确保单元格中的值不是null
                    {
                        var parameterValue = cellValue.ToString();
                        // 触发事件，传递获取到的参数值
                        SelectRow?.Invoke(this, parameterValue);
                    }
                }
            }
        }


        private void LastBageBtn_Click(object sender, EventArgs e)
        {

        }

        private void NextPageBtn_Click(object sender, EventArgs e)
        {

        }

        private void label7_Click(object sender, EventArgs e)
        {

        }

        private void button1_Click(object sender, EventArgs e)
        {

        }

        private void AddBtn_Click(object sender, EventArgs e)
        {
            DoAddData();
         }

        private void DelBtn_Click(object sender, EventArgs e)
        {
            DelGridCol();
        }

        private void EditListBtn_Click(object sender, EventArgs e)
        {
            List<string> stringList = EditListBtn.Tag as List<string>;
            if (stringList == null)
            {
                // 如果不是 List<string>，则使用空列表
                stringList = new List<string>();
            }

            using (dlgEditList dlgEditList = new dlgEditList(stringList))
            {
                WindowAlignmentHelper.Align(this.FindForm(), dlgEditList, WindowAlignmentHelper.Alignment.Center);
                // 显示FormB作为模态对话框
                if (dlgEditList.ShowDialog() == DialogResult.OK)
                {
                    // 如果用户点击保存，获取FormB中的数据
                    string inputData = dlgEditList.InputData;
                    // 进行其他操作，如更新FormA的控件等
                    ReadCustomList(inputData);
                }
            }
        }

        private void EqualTextBox_TextChanged(object sender, EventArgs e)
        {

        }

        private void ReadCfgBtn_Click(object sender, EventArgs e)
        {
            LoadDataBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void UIConfigGrid_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {

        }

        private void InputTextBox_Validating(object sender, System.ComponentModel.CancelEventArgs e)
        {
            string NowValue = DefaultInput.Text;
            string MaxValue = MaxInput.Text;
            string MinValue = MinInput.Text;

            if (!_commonInterface.IsInRange(NowValue, MaxValue, MinValue))
            {
                Logger.Instance.Log($"输入的值不在预设范围内");

                // 如果不合法，将 TextBox 恢复为上一次的合法内容
                DefaultInput.Text = lastValidText;
                // 阻止焦点从TextBox转移，直到输入内容合法
                e.Cancel = true;
            }
            else
            {
                lastValidText = NowValue; // 如果合法，更新 lastValidText
            }
        }

        private void SaveBtn_Click(object sender, EventArgs e)
        {
            SaveBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void UpBtn_Click(object sender, EventArgs e)
        {
            UpBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void DownBtn_Click(object sender, EventArgs e)
        {
            DownBtnClicked?.Invoke(this, EventArgs.Empty);
        }

        private void ChangeBtn_Click(object sender, EventArgs e)
        {
            DoAddData();
        }

        private void pictureBox1_Click(object sender, EventArgs e)
        {
            if (pictureBox1.Image != null)
            {
                PreviewForm previewForm = new PreviewForm(pictureBox1.Image);
                previewForm.Show();  // 打开预览窗口
            }
        }

        private void oSelectPicBtn_Click(object sender, EventArgs e)
        {
            SelectMainViewPic();
        }

        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
            {
                OnCheckedChanged?.Invoke(this, pictureBox1.ImageLocation);
            }
        }

        private void DefaultInput_TextChanged(object sender, EventArgs e)
        {
            OnNumLimitChecked(sender, e);
        }

        private void MaxInput_TextChanged(object sender, EventArgs e)
        {
            OnNumLimitChecked(sender, e);
        }

        private void MinInput_TextChanged(object sender, EventArgs e)
        {
            OnNumLimitChecked(sender, e);
        }

        private void ShowRuleInput_TextChanged(object sender, EventArgs e)
        {

        }
    }
}
